package com.steven.im.widget;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.text.method.ScrollingMovementMethod;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.steven.im.App;
import com.steven.im.R;
import com.steven.im.adapter.IMGroupAdapter;
import com.steven.im.entity.BaseEntity;
import com.steven.im.entity.IMGroupNameEntity;
import com.steven.im.net.MyCallback;
import com.steven.im.net.Task;
import com.steven.im.ui.activity.ConfirmOrderActivity;
import com.steven.im.ui.activity.GoodsDetailActivity;
import com.steven.im.ui.activity.RechargeActivity;
import com.steven.im.utils.DataCleanManager;
import com.steven.im.utils.Downloadutils;
import com.steven.im.utils.SPUtils;
import com.steven.im.utils.ToastUtil;
import com.steven.im.utils.UserUtils;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

import retrofit2.Response;

/**
 * Created by Steven on 2019/1/7.
 * 中间dialog的弹出
 */
public class CenterDialog {
    private Activity activity;
    private AlertDialog.Builder builder;
    private View v;

    public CenterDialog(int layoutId, Activity activity) {
        this.activity = activity;
        this.builder = new AlertDialog.Builder(activity);
        this.v = (LayoutInflater.from(activity)).inflate(layoutId, null);
    }

    /**
     * @param title 标题
     *              简单提示框  格式：内容、取消、确定
     */
    public void showPrompt(String title) {
        TextView content = v.findViewById(R.id.prompt_content);
        content.setText(title);
        TextView btn_sure = v.findViewById(R.id.userConfirm);
        TextView btn_cancel = v.findViewById(R.id.userCancel);
        final Dialog dialog = builder.create();
        Objects.requireNonNull(dialog.getWindow()).setBackgroundDrawableResource(R.color.transparent);
        dialog.show();
        //此处设置位置窗体大小
        dialog.getWindow().setLayout(dip2px(activity, 280), LinearLayout.LayoutParams.WRAP_CONTENT);
        Objects.requireNonNull(dialog.getWindow()).setContentView(v);//自定义布局应该在这里添加，要在dialog.show()的后面
        dialog.getWindow().setGravity(Gravity.CENTER);//可以设置显示的位置
        dialog.setCancelable(false);
        btn_sure.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                dialog.dismiss();
                Task.getApiService().accountLogout().enqueue(new MyCallback<String>(activity) {
                    @Override
                    protected void onSuccess(Response<String> response) {

                        UserUtils.clearUserInfo();
                        activity.finish();
                    }

                    @Override
                    protected void onFailure(Throwable t) {

                    }
                });
            }
        });

        btn_cancel.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                dialog.dismiss();
            }
        });
    }

    /**
     * 清除缓存
     */
    public void showPrompt(final TextView tv_cache) {
        TextView content = v.findViewById(R.id.prompt_content);
        content.setText("确认清楚缓存？");
        TextView btn_sure = v.findViewById(R.id.userConfirm);
        TextView btn_cancel = v.findViewById(R.id.userCancel);
        final Dialog dialog = builder.create();
        Objects.requireNonNull(dialog.getWindow()).setBackgroundDrawableResource(R.color.transparent);
        dialog.show();
        //此处设置位置窗体大小
        dialog.getWindow().setLayout(dip2px(activity, 280), LinearLayout.LayoutParams.WRAP_CONTENT);
        Objects.requireNonNull(dialog.getWindow()).setContentView(v);//自定义布局应该在这里添加，要在dialog.show()的后面
        dialog.getWindow().setGravity(Gravity.CENTER);//可以设置显示的位置
        dialog.setCancelable(false);
        btn_sure.setOnClickListener(new View.OnClickListener() {

            @SuppressLint("SetTextI18n")
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                Map<String, ?> map = SPUtils.getAll(activity);
                DataCleanManager.clearAllCache(App.getContext());//清除缓存
                /*删除完之后 进行保存sharePreferences */
                for (int i = 0; i < map.size(); i++) {
                    Set<? extends Map.Entry<String, ?>> set = map.entrySet();
                    for (Map.Entry<String, ?> entry : set) {
                        SPUtils.put(activity, entry.getKey(), entry.getValue());
                    }
                }
                tv_cache.setText("缓存：" + "0M");
            }
        });

        btn_cancel.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                dialog.dismiss();
            }
        });
    }

    private static int dip2px(Context mContext, float dpValue) {
        final float scale = mContext.getResources()
                .getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    /**
     * @param title 标题
     *              简单提示框  格式：内容、取消、确定
     */
    public void showPrompt(String title, String content) {
        TextView prompt_content = v.findViewById(R.id.prompt_content);
        TextView prompt_title = v.findViewById(R.id.prompt_title);
        prompt_title.setText(title);
        prompt_content.setText(content);
        TextView btn_sure = v.findViewById(R.id.userConfirm);
        TextView btn_cancel = v.findViewById(R.id.userCancel);
        final Dialog dialog = builder.create();
        Objects.requireNonNull(dialog.getWindow()).setBackgroundDrawableResource(R.color.transparent);
        dialog.show();
        //此处设置位置窗体大小
        dialog.getWindow().setLayout(dip2px(activity, 280), LinearLayout.LayoutParams.WRAP_CONTENT);
        Objects.requireNonNull(dialog.getWindow()).setContentView(v);//自定义布局应该在这里添加，要在dialog.show()的后面
        dialog.getWindow().setGravity(Gravity.CENTER);//可以设置显示的位置
        dialog.setCancelable(false);
        btn_sure.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                dialog.dismiss();
                activity.startActivity(new Intent(activity, RechargeActivity.class));
            }
        });

        btn_cancel.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                dialog.dismiss();
            }
        });
    }

    /**
     * @param title 标题
     *              简单提示框  格式：内容、取消、确定
     */
    public void showPrompt_success(String title, String content, final String goodsId, final String saleType) {
        TextView prompt_content = v.findViewById(R.id.prompt_content);
        TextView prompt_title = v.findViewById(R.id.prompt_title);
        prompt_title.setText(title);
        prompt_content.setText(content);
        TextView btn_sure = v.findViewById(R.id.userConfirm);
        TextView btn_cancel = v.findViewById(R.id.userCancel);
        final Dialog dialog = builder.create();
        Objects.requireNonNull(dialog.getWindow()).setBackgroundDrawableResource(R.color.transparent);
        dialog.show();
        //此处设置位置窗体大小
        dialog.getWindow().setLayout(dip2px(activity, 280), LinearLayout.LayoutParams.WRAP_CONTENT);
        Objects.requireNonNull(dialog.getWindow()).setContentView(v);//自定义布局应该在这里添加，要在dialog.show()的后面
        dialog.getWindow().setGravity(Gravity.CENTER);//可以设置显示的位置
        dialog.setCancelable(false);
        btn_sure.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                dialog.dismiss();
                activity.startActivity(new Intent(activity, ConfirmOrderActivity.class).putExtra("my_type", "order")
                        .putExtra("Id", goodsId)
                        .putExtra("salesType", saleType));
            }
        });

        btn_cancel.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                dialog.dismiss();
            }
        });
    }

    /**
     * @param title 标题
     *              简单提示框  格式：内容、取消、确定
     */
    public void showPrompt_fail(String title, String content, final String issuedNo) {
        TextView prompt_content = v.findViewById(R.id.prompt_content);
        TextView prompt_title = v.findViewById(R.id.prompt_title);
        prompt_title.setText(title);
        prompt_content.setText(content);
        TextView btn_sure = v.findViewById(R.id.userConfirm);
        TextView btn_cancel = v.findViewById(R.id.userCancel);
        final Dialog dialog = builder.create();
        Objects.requireNonNull(dialog.getWindow()).setBackgroundDrawableResource(R.color.transparent);
        dialog.show();
        //此处设置位置窗体大小
        dialog.getWindow().setLayout(dip2px(activity, 280), LinearLayout.LayoutParams.WRAP_CONTENT);
        Objects.requireNonNull(dialog.getWindow()).setContentView(v);//自定义布局应该在这里添加，要在dialog.show()的后面
        dialog.getWindow().setGravity(Gravity.CENTER);//可以设置显示的位置
        dialog.setCancelable(false);
        btn_sure.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                //需要判断  是否有下一期  没有下一期  就返回首页
                goNextBidding(issuedNo, dialog);
            }
        });

        btn_cancel.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                dialog.dismiss();
                activity.finish();
            }
        });
    }

    //前往下一期
    private void goNextBidding(String issuedNo, final Dialog dialog) {
        Task.getApiService().nextBid(issuedNo).enqueue(new MyCallback<BaseEntity>(activity) {
            @Override
            protected void onSuccess(Response<BaseEntity> response) {
                if ("0".equals(response.body().getCode())) {
                    //需要重新跳转  到详情页
                    dialog.dismiss();
                    String nextIssuedNo = response.body().getResult().getString("nextIssuedNo");
                    activity.finish();
                    activity.startActivity(new Intent(activity, GoodsDetailActivity.class).putExtra("issuedNo", nextIssuedNo));
                } else {
                    ToastUtil.showShort(activity, response.body().getMessage());
                }
            }

            @Override
            protected void onFailure(Throwable t) {

            }
        });
    }

    /**
     * @param content 更新描述
     * @param type    //更新类型：0.强制更新； 1.推荐更新； -1.H5模式；
     * @param linkUrl //下载 链接
     */
    public void showUpdatePrompt(final Context ctx, String content, String type, final String linkUrl) {
        ImageView close = v.findViewById(R.id.close_dialog);
        TextView tvDesc = v.findViewById(R.id.tv_desc);
        Button update = v.findViewById(R.id.update_now);

        final Dialog dialog = builder.create();
        Objects.requireNonNull(dialog.getWindow()).setBackgroundDrawableResource(R.color.transparent);
        dialog.show();
        //此处设置位置窗体大小
        dialog.getWindow().setLayout(dip2px(activity, 270), LinearLayout.LayoutParams.WRAP_CONTENT);
        Objects.requireNonNull(dialog.getWindow()).setContentView(v);//自定义布局应该在这里添加，要在dialog.show()的后面
        dialog.getWindow().setGravity(Gravity.CENTER);//可以设置显示的位置
        dialog.setCancelable(false);
        if ("0".equals(type)) {
            close.setVisibility(View.GONE);
        }
        tvDesc.setText(content);
        tvDesc.setMovementMethod(ScrollingMovementMethod.getInstance());
        close.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });

        update.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                if (!TextUtils.isEmpty(linkUrl)) {
                    Downloadutils.getInstance().crateFileDownloader(ctx, linkUrl);
                }
                dialog.dismiss();
            }
        });

    }

    /**
     * @param contentList 分组记录
     */
    public void showGroup(List<IMGroupNameEntity> contentList,TextView tvGroupName) {
        RecyclerView recyclerView = v.findViewById(R.id.rc_group);
        LinearLayoutManager manager = new LinearLayoutManager(activity);
        recyclerView.setLayoutManager(manager);
        recyclerView.setAdapter(new IMGroupAdapter(contentList,tvGroupName));
        TextView btn_sure = v.findViewById(R.id.tv_confirm);
        final Dialog dialog = builder.create();
        Objects.requireNonNull(dialog.getWindow()).setBackgroundDrawableResource(R.color.transparent);
        dialog.show();
        //此处设置位置窗体大小
        dialog.getWindow().setLayout(dip2px(activity, 280), LinearLayout.LayoutParams.WRAP_CONTENT);
        Objects.requireNonNull(dialog.getWindow()).setContentView(v);//自定义布局应该在这里添加，要在dialog.show()的后面
        dialog.getWindow().setGravity(Gravity.CENTER);//可以设置显示的位置
        dialog.setCancelable(false);
        btn_sure.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                dialog.dismiss();
                //确定选择此分组
            }
        });

    }
}
